<template>
  <div v-if="loading" class="flex flex-col justify-center items-center h-screen">
    <van-loading size="24px" vertical>数据加载中...</van-loading>
  </div>

  <div class="flex flex-col justify-between pt-6 px-3 h-screen" v-else>
    <div class="bg-white overflow-y-auto flex-auto">
      <!-- 拜访基础信息 -->
      <h1 class="font-bold text-xl">{{ info.subject }}</h1>
      <div class="flex flex-row mt-2 mb-4">
        <div class="tag">{{ info.stageName }}</div>
      </div>
      <!-- 时间卡 -->
      <div
        class="linear flex flex-row items-center justify-between p-2 px-3 mb-4 rounded-md"
      >
        <div class="flex flex-col items-center py-4">
          <span class="mb-2 text-[24px] font-bold">{{ startTime }}</span>
          <span class="text-xs text-[#595959]">{{ startDate }}</span>
        </div>

        <div class="flex flex-row items-center">
          <div class="h-[1px] w-[30px] bg-[#D7E7FF]"></div>
          <div class="bg-[#D7E7FF] px-2 text-[10px] mx-2">{{ scheduleDuration }}</div>
          <div class="h-[1px] w-[30px] bg-[#D7E7FF]"></div>
        </div>

        <div class="flex flex-col items-center py-4">
          <span class="mb-2 text-[24px] font-bold">{{ endTime }}</span>
          <span class="text-xs text-[#595959]">{{ endDate }}</span>
        </div>
      </div>

      <!-- 列表展示内容 -->
      <div class="flex flex-col text-sm text-[#262626]">
        <div class="flex flex-row items-center mb-4">
          <img class="mr-3" src="@/icons/svg/visitDetail/customer.svg" />
          <span class="text-sm text-[#262626]">{{ info.customerName }}</span>
        </div>

        <div
          class="flex flex-row items-center mb-4"
          v-if="info.onlineMeetUrl?.length > 0"
        >
          <img class="mr-3" src="@/icons/svg/visitDetail/meet_room.svg" />
          <div class="flex flex-row w-full items-start justify-between">
            <div @click="openOnlineMeetUrl">
              <div
                class="border border-[#436BFF] rounded-md py-1 px-1 w-[100px] text-center text-[#436BFF]"
              >
                加入会议
              </div>
              <p>{{ info.onlineMeetUrl }}</p>
            </div>

            <img class="ml-2 w-4" src="@/icons/svg/copy.svg" @click="copyOnLineUrl" />
          </div>
        </div>

        <div class="flex flex-row items-start mb-4" v-if="info.salesGoal?.length > 0">
          <img class="mr-3" src="@/icons/svg/visitDetail/target.svg" />
          <p class="text-sm text-[#262626]">
            {{ info.salesGoal }}
          </p>
        </div>

        <div class="flex flex-row items-start mb-4" v-if="!participantListIsEmpty">
          <img class="mr-3" src="@/icons/svg/visitDetail/attend.svg" />
          <div class="flex flex-col">
            <h4 class="mb-2 mt-[2px]" v-if="innerAttendDes">内部参会人</h4>
            <p class="text-sm text-[#8c8c8c] mb-2" v-if="innerAttendDes">
              {{ innerAttendDes }}
            </p>
            <h4 class="mb-2" v-if="cp_showCustomer">客户参会人</h4>
            <p class="text-sm text-[#8c8c8c]" v-if="cp_showCustomer">
              {{ customerAttendDes }}
            </p>
          </div>
        </div>

        <van-divider />
        <div
          class="flex flex-col text-sm text-[#262626]"
          v-if="info.location?.length > 0"
        >
          <div class="flex flex-row items-center mb-4">
            <img class="mr-3" src="@/icons/svg/visitDetail/place.svg" />
            <span class="text-sm text-[#262626]">{{ info.location }}</span>
          </div>
        </div>

        <div class="flex flex-row items-start mb-4" v-if="cp_visitDes.length > 0">
          <img class="mr-3" src="@/icons/svg/visitDetail/target.svg" />
          <div class="flex flex-col items-start mt-[0.5]">
            <p class="text-sm text-[#262626]">
              {{ cp_visitDes }}
            </p>
            <div
              class="flex flex-row items-center mt-1"
              v-show="info.description?.length > 100"
              @click="showDes = !showDes"
            >
              <span class="text-yxt-blue mr-1">{{ showDes ? "收起" : "展开" }}</span>
              <van-icon :name="showDes ? 'arrow-up' : 'arrow-down'" color="#436BFF" />
            </div>
          </div>
        </div>

        <div class="flex flex-row items-start mb-4" v-if="info.fileList?.length > 0">
          <img class="mr-3" src="@/icons/svg/visitDetail/file.svg" />
          <div class="flex flex-col items-start">
            <p>{{ info.fileList.length }}个附件</p>
            <p
              v-for="item in info.fileList"
              :key="item"
              @click="onClickFile(item)"
              class="bg-[#EBEDEE] px-2 py-1 rounded-sm text-xs mt-2"
            >
              {{ item.name }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <div class="flex flex-row justify-between items-center mb-4">
      <van-button
        plain=""
        type="primary"
        size="large"
        color="#436BFF"
        @click="onClickReview"
        v-if="isNeedShowReviewBtn"
        >回顾</van-button
      >
      <div class="w-8"></div>
      <van-button
        plain=""
        type="primary"
        size="large"
        color="#436BFF"
        @click="onClickReady"
        >准备</van-button
      >
      <div class="w-8"></div>

      <van-button
        type="primary"
        size="large"
        color="#436BFF"
        :disabled="disableStartBtn"
        v-if="!isCollaborate && !fromContinue && !isNeedShowReviewBtn"
        @click="onClickStart"
      >
        {{ isNeedShowReviewBtn ? "继续" : "开始" }}</van-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { visitDetailsAPI } from "@/services/orderVisit";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import { showToast } from "vant";
import { previewFileUrl } from "@/utils/urlTool";
import { openMeetingRecord } from "@/utils/urlTool";
import { getUserInfo } from "@/utils/auth";
import { useCommonStore } from "@/store";
const commonStore = useCommonStore();

dayjs.extend(customParseFormat);

const route = useRoute();
const router = useRouter();
const info = ref({});

onMounted(() => {
  getData();
});

const showDes = ref(false);

const cp_visitDes = computed(() => {
  if (!info.value.description) return "";
  return showDes.value ? info.value.description : info.value.description?.slice(0, 100);
});

const startDateTime = computed(() => {
  return dayjs(
    `${info.value.scheduleStartDate} ${info.value.scheduleStartTime}`,
    "" + "YYYY-MM-DD HH:mm"
  );
});

const endDateTime = computed(() => {
  return dayjs(`${info.value.scheduleEndTime}`, "YYYY-MM-DD HH:mm");
});

const scheduleDuration = computed(() => {
  let minutes = endDateTime.value.diff(startDateTime.value, "minute");
  let hours = Math.floor(minutes / 60);
  let mins = minutes % 60;

  let txt = "";
  if (hours > 0) {
    txt += `${hours}小时`;
  }
  if (mins > 0) {
    txt += `${mins}分钟`;
  }
  return txt;
});

const startDate = computed(() => startDateTime.value.format("YYYY年MM月DD日"));
const startTime = computed(() => startDateTime.value.format("HH:mm"));
const endDate = computed(() => endDateTime.value.format("YYYY年MM月DD日"));
const endTime = computed(() => endDateTime.value.format("HH:mm"));

const participantListIsEmpty = computed(() => info.value.participantList?.length === 0);

const innerAttendDes = computed(() => {
  if (JSON.stringify(info.value) === "{}") return [];
  return (
    info.value.participantList
      .filter((v) => {
        return v.attendeeType !== "CUSTOMER_ATTENDEE";
      })
      .map((v) => v.name)
      .join(",") || ""
  );
});

const customerAttendDes = computed(() => {
  if (JSON.stringify(info.value) === "{}") return [];
  let array = info.value.participantList.filter((v) => {
    return v.attendeeType === "CUSTOMER_ATTENDEE";
  });
  return array.map((v) => v.name).join(",") || "";
});

const cp_showCustomer = computed(() => {
  return customerAttendDes.value.length > 0 && cp_isToB.value;
});

const isNeedShowReviewBtn = computed(() => {
  if (info.value.recognitionStatus === "DELETED") {
    return false;
  }
  if (info.value.recognitionPath?.length > 0) {
    return true;
  }
  return false;
});

const isCollaborate = computed(() => {
  return info.value.hostUserId !== getUserInfo().id;
});

const cp_isToB = computed(() => {
  return commonStore.isToB;
});

const loading = ref(false);
const fromContinue = ref(route.query.fromContinue === "1");
async function getData() {
  let scheduleId = route.query.scheduleId;
  loading.value = true;
  const res = await visitDetailsAPI(scheduleId);
  loading.value = false;
  info.value = res;
}

function copyOnLineUrl() {
  navigator.clipboard.writeText(info.value.onlineMeetUrl);
  showToast("复制成功");
}

function onClickFile(item) {
  if (!item.sharePath) {
    showToast("文件地址不存在");
    return;
  }
  router.push({
    name: "previewFile",
    query: { src: item.sharePath },
  });
}

function openOnlineMeetUrl() {
  window.flutter_inappwebview.callHandler("openUrl", info.value.onlineMeetUrl);
}

function onClickReady() {
  router.push({ path: "preVisit", query: route.query });
}

function onClickStart() {
  // 调用Flutter原生方法
  let { upcomingId = "", scheduleId = "" } = info.value;
  let obj = { upcomingId, scheduleId };
  window.flutter_inappwebview.callHandler("handleStart", JSON.stringify(obj));
}

function onClickReview() {
  if (
    info.value.recognitionPath?.length === 0 &&
    info.value.recognitionStatus !== "DELETED"
  ) {
    showToast("正在生成中");
    return;
  }

  let conferenceIdArrary = info.value.conferenceIds.split(",");
  if (conferenceIdArrary.length > 0) {
    openMeetingRecord(conferenceIdArrary[0]);
  } else {
    showToast("会议ID不存在");
  }
}

const disableStartBtn = computed(() => {
  return info.value.inProgress;
});
</script>

<style lang="less" scoped>
.tag {
  color: #436bff;
  background-color: #e6eeff;
  padding: 4px 8px;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 12px;
}

.linear {
  background: linear-gradient(180deg, #e9f1ff 0%, #f5f9ff 100%);
}
</style>
